package com.touch.app.common.filter;

import com.alibaba.fastjson.JSON;
import com.touch.app.common.util.R;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.util.LinkedList;
import java.util.List;

@Slf4j
public class ApiFilter implements Filter {

    private static List<String> URL_LIST = new LinkedList<>();

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
        URL_LIST.add("/");
        URL_LIST.add("/index.html");
        URL_LIST.add("/index");
        URL_LIST.add("/api/ask");
        URL_LIST.add("/api/openai/ask");
        URL_LIST.add("/api/openai/request");
        URL_LIST.add("/api/openai/chat");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        String requestURI = httpRequest.getRequestURI();
        String ip = httpRequest.getRemoteAddr();
        log.info("IP: {}", ip);
        log.info("URI: {}", requestURI);
        if (!URL_LIST.contains(requestURI)) {
            HttpServletResponse httpResponse = (HttpServletResponse) response;
            httpResponse.setStatus(200);
            httpResponse.setContentType("application/json");
            httpResponse.setCharacterEncoding(StandardCharsets.UTF_8.toString());
            PrintWriter writer = httpResponse.getWriter();
            R r = R.error("Access Denied");
            r.setCode(401);
            writer.println(JSON.toJSONString(r));
            writer.close();
        }else {
            chain.doFilter(request,response);
        }
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
